package com.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.MemberCardReplacement;
import com.finance.mapper.MemberCardReplacementMapper;
import com.finance.service.MemberCardReplacementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C14
 * 会员卡补卡换卡数据Service实现类
 */
@Slf4j
@Service
public class MemberCardReplacementServiceImpl extends ServiceImpl<MemberCardReplacementMapper, MemberCardReplacement> implements MemberCardReplacementService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            log.warn("No records to process for C14 data");
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                .eq(MemberCardReplacement::getSearchDate, searchDate)
                .eq(MemberCardReplacement::getCinemaId, cinemaId)
                .count();
            if (count > 0) {
                log.info("C14数据已存在，searchDate: {}, cinemaId: {}, 跳过处理", searchDate, cinemaId);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期的数据
            lambdaUpdate()
                .eq(MemberCardReplacement::getSearchDate, searchDate)
                .eq(MemberCardReplacement::getCinemaId, cinemaId)
                .remove();
        }

        List<MemberCardReplacement> replacementList = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                MemberCardReplacement replacement = new MemberCardReplacement();
                replacement.setCinemaId(cinemaId);
                //影城名称,影城编码,操作时间,订单号,业务类型,旧卡号,旧卡类型,旧卡类型编码,旧卡政策,旧卡政策编码
                if (StringUtils.hasText(record.get("影城名称"))) {
                    replacement.setCinemaName(record.get("影城名称"));
                }
                if (StringUtils.hasText(record.get("影城编码"))) {
                    replacement.setCinemaCode(record.get("影城编码"));
                }
                
                // 处理操作时间
                String operationTimeStr = record.get("操作时间");
                if (StringUtils.hasText(operationTimeStr)) {
                    try {
                        replacement.setOperationTime(LocalDateTime.parse(operationTimeStr, DATE_TIME_FORMATTER));
                    } catch (Exception e) {
                        log.warn("Invalid operation time format: {}", operationTimeStr);
                    }
                }
                if (StringUtils.hasText(record.get("订单号"))) {
                    replacement.setOrderNo(record.get("订单号"));
                }
                if (StringUtils.hasText(record.get("业务类型"))) {
                    replacement.setBusinessType(record.get("业务类型"));
                }
                if (StringUtils.hasText(record.get("旧卡号"))) {
                    replacement.setOldCardNo(record.get("旧卡号"));
                }
                if (StringUtils.hasText(record.get("旧卡类型"))) {
                    replacement.setOldCardType(record.get("旧卡类型"));
                }
                if (StringUtils.hasText(record.get("旧卡类型编码"))) {
                    replacement.setOldCardTypeCode(record.get("旧卡类型编码"));
                }
                if (StringUtils.hasText(record.get("旧卡政策"))) {
                    replacement.setOldCardPolicy(record.get("旧卡政策"));
                }
                if (StringUtils.hasText(record.get("旧卡政策编码"))) {
                    replacement.setOldCardPolicyCode(record.get("旧卡政策编码"));
                }
                // 旧卡余额,新卡号,新卡类型,新卡类型编码,新卡政策,新卡政策编码,应收工本费
                // 处理旧卡余额
                String oldCardBalanceStr = record.get("旧卡余额");
                if (StringUtils.hasText(oldCardBalanceStr)) {
                    try {
                        replacement.setOldCardBalance(new BigDecimal(oldCardBalanceStr));
                    } catch (Exception e) {
                        log.warn("Invalid old card balance format: {}", oldCardBalanceStr);
                    }
                }
                if (StringUtils.hasText(record.get("新卡号"))) {
                    replacement.setNewCardNo(record.get("新卡号"));
                }
                if (StringUtils.hasText(record.get("新卡类型"))) {
                    replacement.setNewCardType(record.get("新卡类型"));
                }
                if (StringUtils.hasText(record.get("新卡类型编码"))) {
                    replacement.setNewCardTypeCode(record.get("新卡类型编码"));
                }
                if (StringUtils.hasText(record.get("新卡政策"))) {
                    replacement.setNewCardPolicy(record.get("新卡政策"));
                }
                if (StringUtils.hasText(record.get("新卡政策编码"))) {
                    replacement.setNewCardPolicyCode(record.get("新卡政策编码"));
                }
                // 处理应收工本费
                String cardFeeStr = record.get("应收工本费");
                if (StringUtils.hasText(cardFeeStr)) {
                    try {
                        replacement.setCardFee(new BigDecimal(cardFeeStr));
                    } catch (Exception e) {
                        log.warn("Invalid card fee format: {}", cardFeeStr);
                    }
                }
                // 实收工本费,支付工具,支付工具编码,操作员,操作员工号,发卡影城名称,发卡影城编码
                // 处理实收工本费
                String actualCardFeeStr = record.get("实收工本费");
                if (StringUtils.hasText(actualCardFeeStr)) {
                    try {
                        replacement.setActualCardFee(new BigDecimal(actualCardFeeStr));
                    } catch (Exception e) {
                        log.warn("Invalid actual card fee format: {}", actualCardFeeStr);
                    }
                }
                if (StringUtils.hasText(record.get("支付工具"))) {
                    replacement.setPaymentTool(record.get("支付工具"));
                }
                if (StringUtils.hasText(record.get("支付工具编码"))) {
                    replacement.setPaymentToolCode(record.get("支付工具编码"));
                }
                if (StringUtils.hasText(record.get("操作员"))) {
                    replacement.setOperator(record.get("操作员"));
                }
                if (StringUtils.hasText(record.get("操作员工号"))) {
                    replacement.setOperatorEmployeeNo(record.get("操作员工号"));
                }
                if (StringUtils.hasText(record.get("发卡影城名称"))) {
                    replacement.setIssueCinemaName(record.get("发卡影城名称"));
                }
                if (StringUtils.hasText(record.get("发卡影城编码"))) {
                    replacement.setIssueCinemaCode(record.get("发卡影城编码"));
                }
                replacement.setSearchDate(searchDate);
                
                replacementList.add(replacement);
            } catch (Exception e) {
                log.error("Error processing C14 record: {}", record, e);
                throw new RuntimeException("Failed to process C14 record", e);
            }
        }

        try {
            saveBatch(replacementList);
            return replacementList.size();
        } catch (Exception e) {
            log.error("Error saving C14 data batch", e);
            throw new RuntimeException("Failed to save C14 data batch", e);
        }
    }
} 